//
//  TJQuickTradingNewController.m
//  Teleport
//
//  Created by botu　 on 2020/7/24.
//  Copyright © 2020 byx. All rights reserved.
//

#import "TJQuickTradingNewController.h"
#import "TJOrderDetailControntroller.h"
@interface TJQuickTradingNewController ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UIView *numBgView;
/**数量 */
@property (weak, nonatomic) IBOutlet UITextField *numTextField;
/**币子名称 */
@property (weak, nonatomic) IBOutlet UILabel *coinName;


@property (weak, nonatomic) IBOutlet UIView *moneyBgView;
/**总金额 */
@property (weak, nonatomic) IBOutlet UITextField *moneyTextField;
@property (weak, nonatomic) IBOutlet UIButton *buyBtutton;
@property (weak, nonatomic) IBOutlet UIView *payIconBgView;
/**价格 */
@property (weak, nonatomic) IBOutlet UILabel *priceLabel;

@property (weak, nonatomic) IBOutlet UILabel *coinNameLabel;
/**限额 */
@property (weak, nonatomic) IBOutlet UILabel *limitLabel;
/**可用 购买隐藏 */
@property (weak, nonatomic) IBOutlet UILabel *availableLabel;

/**倒计时 */
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;


// 商家信息

@property (weak, nonatomic) IBOutlet UILabel *storeName;

@property (weak, nonatomic) IBOutlet UILabel *storeNickName;
/**完成率 */
@property (weak, nonatomic) IBOutlet UILabel *storeRoat;
/**认证状态 */
@property (weak, nonatomic) IBOutlet UILabel *storeStatus;
/**放币时效 */
@property (weak, nonatomic) IBOutlet UILabel *storeTime;

/**0我要买 1 我要卖 **/
@property (assign, nonatomic) int type;



@end

@implementation TJQuickTradingNewController
{
    dispatch_source_t _sendSMSTimer;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.navigationBar.backgroundColor = UIColor_Hex(0x2C6CC7);
    self.navigationBar.lineView.hidden = YES;
    [self.navigationBar backBarButtonWhiteColor];
    self.navigationBar.titleTextColor = UIColor.whiteColor;
    
    [self.numBgView addRoundedLine];
    [self.moneyBgView addRoundedLine];
    self.numTextField.delegate = self;
    self.moneyTextField.delegate = self;
    [self.numTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [self.moneyTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    //倒计时
    [self startCountdown];
    
    
    if ([self.model.direction isEqualToString:@"SELL"]) {//购买
        self.type = 0;
    }else{//出售
        self.type = 1;
        self.availableLabel.hidden = NO;
        //获取账户可用资产
        [self loadAvailable:self.model.currency];
    }
    
    NSString *typeStr = self.type == 0 ?@"购买".localizedString : @"出售".localizedString;
    self.navigationBar.title = [NSString stringWithFormat:@"%@%@",typeStr,self.model.currency];
    [self.buyBtutton setTitle:typeStr forState:UIControlStateNormal];
    
    /**z加载支付方式图标 */
    [self payIconImages];
    
    
    self.priceLabel.text = [NSString stringWithFormat:@"¥%@",self.model.nowPrice];
    self.coinNameLabel.text = [NSString stringWithFormat:@"/%@",self.model.currency];
    self.coinName.text = self.model.currency;
    
    
    self.limitLabel.text = [NSString stringWithFormat:@" %@\n ¥%@~¥%@", @"限额".localizedString, self.model.minPrice,[self getMaxMoney]];
    
    
    
    //获取商家信息
    [self loadStoreMessage];
    
}

/**总数量按钮点击 */
- (IBAction)allNumBtnClick:(UIButton *)sender {
    self.numTextField.text = self.model.num;
    [self textFieldDidChange:self.numTextField];
    //计算总金额
    [self calculateAllMoney];
}
/**总金额按钮点击 */
- (IBAction)allMoneyBtnClick:(UIButton *)sender {
    
    self.moneyTextField.text = [self getMaxMoney];
    [self textFieldDidChange:self.moneyTextField];
    
    //计算数量
    [self calculateNum];
}

- (IBAction)buyBtnClick:(UIButton *)sender {
    [self.view endEditing:YES];
    TJLog(@"=====");
    
    if (self.type == 0) {//购买
        
    }else{//出售
        
        if ([self.availableLabel.text doubleValue] < self.numTextField.text.doubleValue) {
            NSString *str = [NSString stringWithFormat:@"账户可用数量为:%@",self.availableLabel.text];
            [TJHud showAutoHideMessage:str];
            return;
        }
    }
    
    if ([self.moneyTextField.text doubleValue] < self.model.minPrice.doubleValue) {
        [TJHud showAutoHideMessage:@"总金额过小".localizedString];
        return;
    }
    NSString *maxMoney = [self getMaxMoney];
    if ([self.moneyTextField.text doubleValue] > maxMoney.doubleValue) {
        [TJHud showAutoHideMessage:@"总金额过大".localizedString];
        return;
    }
    
    NSDictionary *parameters = @{
        @"userId": TJUserInfo.readInfo.userId,
        @"orderId": self.model.id,
        @"type": @"PRICE",
        @"num":self.moneyTextField.text
    };
    
    [self showloading];
    weakify(self)
    [TJNetworking.shareNetworking POSTNew:@"otc/order/placeAnOrder" parameters:parameters success:^(NSDictionary * _Nonnull responseObject, NSDictionary *data) {
        
        [weakself hiddenloading];
        
        NSString *orderId = data[@"orderPriceId"];
        if (orderId == nil) {
            [TJHud showTopAutoHideMessage:@"下单异常,请重新下单".localizedString];
            return ;
        }
        [weakself.navigationController popViewControllerAnimated:NO];
        //跳转订单详情
        TJOrderDetailControntroller *orderVC = [TJOrderDetailControntroller new];
        orderVC.orderId  = orderId;
        [[Tools currentNavController] pushViewController:orderVC animated:YES];
        
    } failure:^(NSError * _Nonnull error) {
        [weakself hiddenloading];
        [TJHud showAutoHideMessage:error.localizedFailureReason];
        
    }];
}

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(nonnull NSString *)string {
    
    if (textField == self.numTextField || textField == self.moneyTextField) {
        // 限制第一位不能是小数点
        if(textField.text.length == 0 && [string isEqualToString:@"."])return NO;
        //第一位补位零
        if(textField.text.length == 0 && [string isEqualToString:@"0"])return NO;
        
    }
    
    return  YES;
    
}
- (void)textFieldDidChange:(UITextField *)textField {
    
    //计算总金额
    if (textField == self.numTextField) {
        [self calculateAllMoney];
    }
    //计算数量
    if (textField == self.moneyTextField){
        [self calculateNum];
    }
    
    if (self.numTextField.text.length && self.moneyTextField.text.length) {
        
        if (self.type == 0) {//购买
            self.buyBtutton.backgroundColor = UIColor.tj_mainColor;
        }else{//出售
            self.buyBtutton.backgroundColor= UIColor_Hex(0xDA2629);
        }
        self.buyBtutton.enabled = YES;
    }else{
        
        
        self.buyBtutton.backgroundColor =UIColor_Hex(0xC6C6C8);
        self.buyBtutton.enabled = NO;
    }
    
}
/**加载支付方式图标 */
-(void)payIconImages {
    
    NSArray*array = [self.model.payType componentsSeparatedByString:@"-"];
    NSMutableArray *payWayIconDatas = @[].mutableCopy;
    for (NSString *payName in array) {
        if ([payName isEqualToString:@"WECHAT"]) {
            [payWayIconDatas addObject:@"OTC_list_weChat"];
        }
        if ([payName isEqualToString:@"ALIAY"]) {
            [payWayIconDatas addObject:@"OTC_list_Alipay"];
        }
        if ([payName isEqualToString:@"BANKCARD"]) {
            [payWayIconDatas addObject:@"OTC_list_bank"];
        }
        
    }
    
    int margeX = 5;
    CGFloat imageW = 12;
    for (int i = 0; i < payWayIconDatas.count; i++) {
        UIImageView *imageV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:payWayIconDatas[i]]];
        [self.payIconBgView addSubview:imageV];
        CGFloat imageX =self.payIconBgView.frame.size.width - i * (imageW + margeX);
        imageV.frame = CGRectMake(imageX, 0, imageW, imageW);
        
    }
    
}

- (NSString *)getMaxMoney {
    NSString *maxMoneyStr = [NSString stringWithFormat:@"%f",self.model.nowPrice.doubleValue * self.model.num.doubleValue];
    return  [Tools CNYString:maxMoneyStr];
}
// 获取商家信息
-(void)loadStoreMessage {
    weakify(self)
    [TJNetworking.shareNetworking GET:@"otc/order/getStoreMsg" parameters:@{@"userId":self.model.member ?: @""} success:^(NSDictionary * _Nonnull responseObject, NSDictionary *data) {
        
        weakself.storeNickName.text = weakself.model.memberFbName;
        weakself.storeRoat.text = [NSString stringWithFormat:@"%ld%%",[data[@"roat"] integerValue]];
        NSInteger second = [data[@"time"] integerValue];
        NSInteger branch =  second/60;
        NSInteger finSecond = second % 60;
        weakself.storeTime.text = [NSString stringWithFormat:@"%ld'%ld\"",branch,finSecond];
        
    } failure:^(NSError * _Nonnull error) {
        
        [TJHud showAutoHideMessage:error.localizedFailureReason];
    }];
}
//获取账户可用资产
- (void)loadAvailable:(NSString *)coinName{
    
    weakify(self)
    [TJNetworking.shareNetworking GET:@"member/balance/getBalanceList" parameters:@{@"currency":coinName,@"userId":TJUserInfo.readInfo.userId} success:^(NSDictionary * _Nonnull responseObject, NSDictionary *data) {
        NSArray *balances = data[@"balances"];
        NSDictionary *dic = balances.firstObject;
        weakself.availableLabel.text = [NSString stringWithFormat:@"%@\n账号可用(%@)",[dic[@"fbBalance"] stringValue],coinName];
        
    } failure:^(NSError * _Nonnull error) {
        
        [TJHud showAutoHideMessage:error.localizedFailureReason];
    }];
}
/**倒计时 */
- (void)startCountdown {
    weakify(self)
    __block NSInteger timestamp = 60;
    
    dispatch_source_t sendSMSTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(0, 0));
    dispatch_source_set_timer(sendSMSTimer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(sendSMSTimer, ^{
        
        timestamp--;
        
        if (timestamp <= 0) {
            dispatch_source_cancel(sendSMSTimer);
            dispatch_async(dispatch_get_main_queue(), ^{//显示GO
                
                [weakself.navigationController popViewControllerAnimated:YES];
                
            });
        } else {
            dispatch_async(dispatch_get_main_queue(), ^{
                weakself.timeLabel.text = [NSString stringWithFormat:@"%ld", timestamp];
                
            });
        }
    });
    _sendSMSTimer = sendSMSTimer;
    dispatch_resume(sendSMSTimer);
}

//计算总金额
- (void)calculateAllMoney{
    double money = self.numTextField.text.doubleValue * self.model.nowPrice.doubleValue;
    
    NSString *moneyStr = [NSString stringWithFormat:@"%f",money];
    self.moneyTextField.text = [Tools CNYString:moneyStr];
}
//计算数量
- (void)calculateNum{
    double num = self.moneyTextField.text.doubleValue / self.model.nowPrice.doubleValue;
    
    NSString *numStr = @"";
    //btc 保留6位 usdt 保留2位
    if ([self.model.currency isEqualToString:@"USDT"]) {
        numStr = [NSString stringWithFormat:@"%.2f",num];
    }else{
        numStr = [NSString stringWithFormat:@"%.6f",num];
    }
    self.numTextField.text = numStr;
}
- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

@end
